//
//  PersonalDataViewController.swift
//  YLH
//
//  Created by qinjiangtao on 2024/1/11.
//

import UIKit
import BRPickerView

class PersonalDataViewController: QIBaseViewController {
    
    var userModel = QIUserModel()
    private var avatarBtn = UIButton()
    private var titleArr = [String]()
    private var rightArr = [String]()
    private var coverUrl = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "个人资料"
        
        addUI()
    }
    
    
    private func addUI() {
        navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.black]
        
        titleArr = ["姓名", "出生日期", "身高", "所在城市", "邮箱号", "手机号", "微信号"]
        rightArr = [userModel.nickname, userModel.birthday, userModel.height, userModel.city, userModel.email, userModel.mobile, userModel.wechat_openid.count > 0 ? "已绑定" : ""]
        coverUrl = userModel.avatar
        
        let titleL1 = UILabel().then({
            $0.frame = CGRect(x: 16, y: NAV_HEIGHT + 13, width: 40, height: 20)
            $0.text = "头像"
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 14)
        })
        view.addSubview(titleL1)
        
        let titleL2 = UILabel().then({
            $0.frame = CGRect(x: 16, y: titleL1.bottom + 5, width: 200, height: 20)
            $0.text = "建议使用真实的照片作为头像"
            $0.textColor = Color999999
            $0.font = SYSFONT(ofSize: 14)
        })
        view.addSubview(titleL2)
        
        avatarBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH - 88, y: NAV_HEIGHT + 12, width: 44, height: 44)
            $0.setImage(UIImage(named: "noo"), for: .normal)
            $0.imageView?.contentMode = .scaleAspectFill
            $0.addRoundedCorners(withRadius: 22)
            $0.addTarget(self, action: #selector(avatarBtnClick), for: .touchUpInside)
        }
        view.addSubview(avatarBtn)
        avatarBtn.kf.setImage(with: URL(string: "\(IMAGE_URL)\(coverUrl)"), for: .normal, placeholder: UIImage(named: "noo"))
        
        let rightBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH - 44, y: avatarBtn.top, width: 44, height: 44)
            $0.setImage(UIImage(named: "箭头右"), for: .normal)
            $0.addTarget(self, action: #selector(avatarBtnClick), for: .touchUpInside)
        }
        view.addSubview(rightBtn)
        
        view.addSubview(tableView)
        
        let modifyBtn = UIButton().then {
            $0.frame = CGRect(x: 20, y: SCREEN_HEIGHT - 90, width: SCREEN_WIDTH - 40, height: 40)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = SYSFONT(ofSize: 14)
            $0.setTitle("确认修改", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 20)
            $0.addTarget(self, action: #selector(modifyBtnClick), for: .touchUpInside)
        }
        view.addSubview(modifyBtn)
    }
    
    @objc private func avatarBtnClick() {
        let alertCtl = UIAlertController(title: "选项", message: "", preferredStyle: .actionSheet)
        alertCtl.addAction(UIAlertAction(title: "拍照", style: .default, handler: { (_) in
            let imagePickerCtl = UIImagePickerController()
            imagePickerCtl.delegate = self
            imagePickerCtl.allowsEditing = true
            imagePickerCtl.sourceType = .camera
            self.present(imagePickerCtl, animated: true)
        }))
        alertCtl.addAction(UIAlertAction(title: "从手机相册选择", style: .default, handler: { (_) in
            let imagePickerCtl = UIImagePickerController()
            imagePickerCtl.delegate = self
            imagePickerCtl.allowsEditing = true
            imagePickerCtl.sourceType = .savedPhotosAlbum
            self.present(imagePickerCtl, animated: true)
        }))
        alertCtl.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
            
        }))
        self.present(alertCtl, animated: true)
    }
    
    @objc private func modifyBtnClick() {
        guard rightArr.count > 6 else {
            return
        }
        
        let nameStr = "\(rightArr[0])"
        let birthdayStr = "\(rightArr[1])"
        let heightStr = "\(rightArr[2])"
        let cityStr = "\(rightArr[3])"
        let emailStr = "\(rightArr[4])"
        
        guard coverUrl.count > 10 else {
            ShowHUD(str: "请选择头像")
            return
        }
        guard nameStr.count > 0 else {
            ShowHUD(str: "请输入您的姓名")
            return
        }
        guard birthdayStr.count > 0 else {
            ShowHUD(str: "请选择出生日期")
            return
        }
        guard heightStr.count > 0 else {
            ShowHUD(str: "请选择身高")
            return
        }
        guard cityStr.count > 0 else {
            ShowHUD(str: "请选择所在城市")
            return
        }
        guard emailStr.count > 0 else {
            ShowHUD(str: "请输入您的邮箱号")
            return
        }
        
        let parame = [
            "nickname": nameStr,
            "avatar": coverUrl,
            "birthday": birthdayStr,
            "height": heightStr,
            "city": cityStr,
            "email": emailStr
        ]
        QINetworkManager.requestJson(urlStr: "/User/editUserInfo", parameters: parame) { json in
            print(json)
            ShowHUD(str: "修改成功!")
            
        }
    }
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.frame = CGRect(x: 0, y: NAV_HEIGHT + 80, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - NAV_HEIGHT - 180)
        tableView.backgroundColor = .white
//        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        } else {}
        return tableView
    }()

}

extension PersonalDataViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titleArr.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        50
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.selectionStyle = .none
        cell.accessoryType = .disclosureIndicator
        let titleStr = titleArr[indexPath.row]
        cell.textLabel?.text = titleStr
        cell.textLabel?.textColor = Color333333
        cell.textLabel?.font = SYSFONT(ofSize: 15)
        
        if titleStr == "姓名" || titleStr == "邮箱号" {
            let leftView = UIView()
            leftView.frame = CGRect(x: 0, y: 0, width: 10, height: 0)
            let TextF = UITextField().then {
                $0.frame = CGRect(x: 100, y: 0, width: SCREEN_WIDTH - 144, height: 44)
                $0.font = SYSFONT(ofSize: 15)
                $0.tag = titleStr.count
                $0.placeholder = "请输入\(titleStr)"
                $0.text = rightArr[indexPath.row]
                $0.textColor = Color333333
                $0.textAlignment = .right
                $0.leftView = leftView
                $0.leftViewMode = .always
                $0.addTarget(self, action: #selector(saveTextFieldInfo(textF: )), for: .editingDidEnd)
            }
            cell.addSubview(TextF)
        } else {
            let rightL = UILabel().then({
                $0.frame = CGRect(x: 100, y: 0, width: SCREEN_WIDTH - 144, height: 44)
                $0.text = "请选择\(titleStr)"
                $0.textColor = Color999999
                $0.textAlignment = .right
                $0.font = SYSFONT(ofSize: 15)
            })
            cell.addSubview(rightL)
            let rightStr = rightArr[indexPath.row]
            if rightStr.count > 0 {
                rightL.text = rightStr
                rightL.textColor = Color333333
            }
            if titleStr == "微信号" {
                rightL.text = userModel.wechat_openid.count > 0 ? "已绑定" : "请绑定微信号"
            }
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let titleStr = titleArr[indexPath.row]
        if titleStr == "出生日期" {
            let dateView = BRDatePickerView()
            dateView.pickerMode = .YMD
            dateView.title = "出生日期"
            dateView.resultBlock = {selectDate, selectValue in
                print(selectValue ?? "")
                self.rightArr[indexPath.row] = selectValue ?? ""
                self.tableView.reloadData()
            }
            dateView.show()
        } else if titleStr == "身高" {
            var heightArr = [String]()
            for h in 100...220 {
                heightArr.append("\(h) cm")
            }
            let stringPickerView = BRStringPickerView(pickerMode: .componentSingle)
            stringPickerView.title = "身高"
            stringPickerView.dataSourceArr = heightArr
            stringPickerView.selectIndex = 70
            stringPickerView.resultModelBlock = {resultModel in
                print(resultModel?.value ?? "")
                self.rightArr[indexPath.row] = resultModel?.value ?? ""
                self.tableView.reloadData()
            }
            stringPickerView.show()
        } else if titleStr == "所在城市" {
            let addressPickerView = BRAddressPickerView(pickerMode: .area)
            addressPickerView.title = "请选择所在地区"
            addressPickerView.resultBlock = { province, city, area in
                let addressStr = "\(province?.name ?? "")/\(city?.name ?? "")/\(area?.name ?? "")"
                print(addressStr)
                self.tableView.reloadData()
                self.rightArr[indexPath.row] = addressStr
            }
            addressPickerView.show()
        } else if titleStr == "手机号" {
            let ctl = MyBindingPhoneViewController()
            navigationController?.pushViewController(ctl, animated: true)
        } else if titleStr == "微信号" {
            if userModel.wechat_openid.count <= 0 {
                let bindingView = BindingWeChatView(frame: CGRect(x: 0, y: SCREEN_HEIGHT - 280, width: SCREEN_WIDTH, height: 280))
                QINPopUpTool.sharedInstance().popUp(with: bindingView, withToViewCtl: self, withAnimation: .bottom, withCanTapBgCancel: true, closeBefore: .node)
            }
        }
    }
    
    @objc func saveTextFieldInfo(textF: UITextField) {
        print(textF.text ?? "")
        if textF.tag == 2 {
            rightArr[0] = textF.text ?? ""
        } else {
            rightArr[4] = textF.text ?? ""
        }
    }
    
}


extension PersonalDataViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image: UIImage = info[UIImagePickerController.InfoKey.editedImage] as! UIImage
        avatarBtn.setImage(image, for: .normal)
        updateImage(img: image)
        picker.dismiss(animated: true)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true)
    }
    private func updateImage(img: UIImage) {
        QINetworkManager.uploadImage(urlStr: "", image: img, success: { json in
            print(json)
            self.coverUrl = "\(json["url"] ?? "")"
        })
    }
    
}
